<template>
  <div class="common-layout">
    <el-container>
      <el-aside width="200px">
<!-- 在表格上方添加当前选中状态提示 -->
<el-alert 
  v-if="selectedTeamId" 
  type="info" 
  closable
  style="margin-bottom: 15px">
  当前查看团队ID:{{ selectedTeamId }}
</el-alert>
        <el-input
    v-model="filterText"
    class="w-60 mb-2"
    placeholder="请输入医院"/>
<!--树形显示-->
  <el-tree
    ref="treeRef"
    style="max-width: 600px"
    class="filter-tree"
    :data="data"
    :props="defaultProps"
    default-expand-all
    :filter-node-method="filterNode"
    @node-click="handleNodeClick"
    highlight-current
  node-key="teamID"
  :current-node-key="selectedTeamId"/><!-- 添加点击事件 -->
        
      </el-aside>
      <el-container>
        <el-header>
          <!--条件查询-->
          <el-form :inline="true" :model="form" class="demo-form-inline">
  <el-form-item label="团队名称">
    <el-input v-model="form.TeamName" placeholder="请输入团队名称" clearable />
  </el-form-item>

  <el-form-item label="状态">
    <el-select
      v-model="form.TeamStatus"
      placeholder="请输入状态"
      clearable style="width: 150px;">
      <el-option label="启用" :value="true" />
      <el-option label="禁用" :value="false" />
    </el-select>
  </el-form-item>

  <el-form-item>
    <el-button type="primary" @click="getTeamInfo()">查询</el-button>
  </el-form-item>

          </el-form>
        </el-header>
        <el-main>
          
          <el-button style="background-color: yellowgreen;"  plain @click="dialogFormVisible = true">添加</el-button>
<!--添加弹出框-->
<el-dialog v-model="dialogFormVisible" title="团队管理的添加" width="850" draggable>
  <el-form :model="teamform">
   <tr>
    <td>
      <span style="color: red;">团队信息</span>
    <el-form-item label="团队名称" :label-width="formLabelWidth">
      <el-input v-model="teamform.teamName" autocomplete="off" placeholder="请输入团队名称"/>
    </el-form-item>

    <el-form-item label="上级团队" :label-width="formLabelWidth">
      <el-select v-model="teamform.teamPardName" placeholder="请输上级团队">
        <el-option label="李伟团队" value="李伟团队" />
        <el-option label="李清照团队" value="李清照团队" />
        <el-option label="李自成团队" value="李自成团队" />
        <el-option label="张鑫团队" value="张鑫团队" />
      </el-select>
    </el-form-item>

    <el-form-item label="团队标签">
    <el-checkbox-group v-model="teamform.teamTags">
      <el-checkbox value="高血压" name="teamTags">
        高血压
      </el-checkbox>
      <el-checkbox value="糖尿病" name="teamTags">
        糖尿病
      </el-checkbox>
      <el-checkbox value="高血脂" name="teamTags">
        高血脂
      </el-checkbox>
      <el-checkbox value="肥胖病" name="teamTags">
        肥胖病
      </el-checkbox><el-checkbox value="高尿酸" name="teamTags">
        高尿酸
      </el-checkbox>
    </el-checkbox-group>
  </el-form-item>

  <el-form-item label="联系电话" :label-width="formLabelWidth">
      <el-input v-model="teamform.contactPhone" autocomplete="off" placeholder="请输入联系电话"/>
    </el-form-item>

    <el-form-item label="团队简介">
    <el-input v-model="teamform.teamIntroduction" type="textarea" />
    </el-form-item>
    </td>
    <td>
      <span style="color: red; margin-left: 10px;" >团队成员</span>
      <el-button type="primary" @click="showMemberDialog">选择</el-button>

<!-- 成员选择对话框 -->
<el-dialog v-model="memberDialogVisible" title="选择人员" width="600" draggable>
  <el-table ref="memberTableRef" :data="membersData" style="width: 100%">
    <el-table-column type="selection"  />  
    <el-table-column prop="userId" label="ID" />
    <el-table-column prop="nickName" label="姓名" />
    <el-table-column prop="sex" label="性别" >
      <template v-slot="scope">
{{ scope.row.sex?"男":"女" }}
      </template>
    </el-table-column>
  </el-table>
  <template #footer>
    <el-button @click="memberDialogVisible = false">取消</el-button>
    <el-button type="primary" @click="confirmMembers">确定</el-button>
  </template>
</el-dialog>


<el-form-item label="姓名" :label-width="formLabelWidth">
<el-input 
  v-model="teamform.teamMembers" 
  autocomplete="off" 
  placeholder="请输入姓名"
  readonly /> <!-- 建议设置为只读，通过选择按钮操作 -->
</el-form-item>

    <el-form-item label="负责人" :label-width="formLabelWidth">     
      <el-select v-model="teamform.teamLeader" autocomplete="off" placeholder="请输入负责人">
        <el-option label="李念云" value="李念云" />
        <el-option label="李自成" value="李自成" />
        <el-option label="张三" value="张三" />
        <el-option label="王东暄" value="王东暄" />
        <el-option label="张靖威" value="张靖威" />
      </el-select>
    </el-form-item>

    <el-form-item label="机构名称" :label-width="formLabelWidth">
      <el-input v-model="teamform.orgName" autocomplete="off" placeholder="请输入机构名称"/>
    </el-form-item>

    <el-form-item label="上级机构名称" :label-width="formLabelWidth">      
      <el-select v-model="teamform.orgNamePard" autocomplete="off" placeholder="请输入上级机构名称">
        <el-option label="中心医院" :value="1" />
        <el-option label="镇卫生院" :value="2" />
        <el-option label="社区卫生中心" :value="3" />
        <el-option label="镇卫生室" :value="4" />
        <el-option label="社区卫生室" :value="5" />
      </el-select>
    </el-form-item>
    
</td>
  </tr>

  </el-form>
  <template #footer>
    <div class="dialog-footer">
      <el-button @click="dialogFormVisible = false">关闭</el-button>
      <el-button type="primary" @click="AddTeamInfo()">
        添加
      </el-button>
    </div>
  </template>
</el-dialog>

<!--修改弹出框-->
<el-dialog v-model="dialogFormUdp" title="团队管理的修改" width="850" draggable>
  <el-form :model="teaminfo">
   <tr>
    <td>
      <span style="color: red;">团队信息</span>
    <el-form-item label="团队名称" :label-width="formLabelWidth">
      <el-input v-model="teaminfo.teamName" autocomplete="off" placeholder="请输入团队名称"/>
    </el-form-item>

    <el-form-item label="上级团队" :label-width="formLabelWidth">
      <el-select v-model="teaminfo.teamPardName" placeholder="请输上级团队">
        <el-option label="李伟团队" value="李伟团队" />
        <el-option label="李清照团队" value="李清照团队" />
        <el-option label="李自成团队" value="李自成团队" />
      </el-select>
    </el-form-item>

    <el-form-item label="团队标签">
    <el-checkbox-group v-model="teaminfo.teamTags">
      <el-checkbox value="高血压" name="teamTags">
        高血压
      </el-checkbox>
      <el-checkbox value="糖尿病" name="teamTags">
        糖尿病
      </el-checkbox>
      <el-checkbox value="高血脂" name="teamTags">
        高血脂
      </el-checkbox>
      <el-checkbox value="肥胖病" name="teamTags">
        肥胖病
      </el-checkbox><el-checkbox value="高尿酸" name="teamTags">
        高尿酸
      </el-checkbox>
    </el-checkbox-group>
  </el-form-item>

  <el-form-item label="联系电话" :label-width="formLabelWidth">
      <el-input v-model="teaminfo.contactPhone" autocomplete="off" placeholder="请输入联系电话"/>
    </el-form-item>

    <el-form-item label="团队简介">
    <el-input v-model="teaminfo.teamIntroduction" type="textarea" />
    </el-form-item>
    </td>
    <td>
      <span style="color: red; margin-left: 10px;" >团队成员</span>
      <el-button type="primary" @click="showMemberDialog">选择</el-button>

<!-- 成员选择对话框 -->
<el-dialog v-model="memberDialogVisible" title="选择人员" width="600" draggable>
  <el-table ref="memberTableRef" :data="membersData" style="width: 100%">
    <el-table-column type="selection"  />  
    <el-table-column prop="userId" label="ID" />
    <el-table-column prop="nickName" label="姓名" />
    <el-table-column prop="sex" label="性别" >
      <template v-slot="scope">
{{ scope.row.sex?"男":"女" }}
      </template>
    </el-table-column>
  </el-table>
  <template #footer>
    <el-button @click="memberDialogVisible = false">取消</el-button>
    <el-button type="primary" @click="confirmMembers">确定</el-button>
  </template>
</el-dialog>


<el-form-item label="姓名" :label-width="formLabelWidth">
<el-input 
  v-model="teaminfo.teamMembers" 
  autocomplete="off" 
  placeholder="请输入姓名"
  readonly /> <!-- 建议设置为只读，通过选择按钮操作 -->
</el-form-item>

    <el-form-item label="负责人" :label-width="formLabelWidth">
      <el-select v-model="teaminfo.teamLeader" autocomplete="off" placeholder="请输入负责人">
        <el-option label="李念云" :value="1" />
        <el-option label="李自成" :value="2" />
        <el-option label="张三" :value="3" />
      </el-select>
    </el-form-item>

    <el-form-item label="机构名称" :label-width="formLabelWidth">
      <el-input v-model="teaminfo.orgName" autocomplete="off" placeholder="请输入机构名称"/>
    </el-form-item>

    <el-form-item label="上级机构名称" :label-width="formLabelWidth">
      <el-select v-model="teaminfo.orgNamePard" autocomplete="off" placeholder="请输入上级机构名称">
        <el-option label="中心医院" :value="0" />
        <el-option label="中心医院" :value="1" />
        <el-option label="镇卫生院" :value="2" />
        <el-option label="社区卫生中心" :value="3" />
        <el-option label="镇卫生室" :value="4" />
        <el-option label="社区卫生室" :value="5" />
      </el-select>
    </el-form-item>
    
</td>
  </tr>

  </el-form>
  <template #footer>
    <div class="dialog-footer">
      <el-button @click="dialogFormUdp = false">关闭</el-button>
      <el-button type="primary" @click="UdpTeamInfo()">
        更改
      </el-button>
    </div>
  </template>
</el-dialog>
<!--团队管理列表-->
          <el-table :data="tableData" style="width: 100%">
  <el-table-column  prop="teamID" label="编号" width="150" />
  <el-table-column  prop="teamName" label="团队名称" width="150" />
  <el-table-column prop="teamPardName" label="上级团队" width="120" />
  <el-table-column prop="teamLeader" label="负责人" width="120" />
  <el-table-column prop="teamTags" label="团队标签" width="120" />
  <el-table-column prop="teamStatus" label="状态" width="120" >
      <template v-slot="scoped">
        <el-tag  effect="dark" round>
      {{scoped.row.teamStatus?"启用":"禁用" }}
       </el-tag>        
      </template>
  </el-table-column>
  <el-table-column fixed="right" label="操作" min-width="120">
    <template v-slot="scope">
      <el-button style="background-color:red;"  plain @click="DelTeamInfo(scope.row.teamID)">删除</el-button>
      <el-button style="background-color:blue;" plain  :type="scope.row.teamStatus? 'danger' :'success'" size="small"
                 @click="UdpTeamStatus(scope.row.teamID)"
                 :label="scope.row.teamStatus? '禁用' :'启用'">
      {{scope.row.teamStatus? '禁用' :'启用'}}
    </el-button>   
    <el-button style="background-color: yellowgreen;"  plain @click="fantian(scope.row)">修改</el-button>
    
    </template>
  </el-table-column>
</el-table>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>
 
<script setup lang="ts">
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import moment from 'moment';
import { onMounted, reactive, ref,watch } from 'vue'
import { useRouter, useRoute } from 'vue-router';
import { regionData } from "element-china-area-data";//引入
import { useCounterStore } from '@/stores/counter';
import type { TreeInstance } from 'element-plus'
const apiUrl = import.meta.env.VITE_APP_API_URL;
// console.log(regionData)
//pini保存
const store = useCounterStore();
//跳转
const router = useRouter();
const formLabelWidth = '140px'
//查询参数
const form = reactive({
  TeamName:"",
  TeamStatus:null
})

//列表数据
const tableData = ref([])
const getTeamInfo= ()=>{
  axios.get(apiUrl+'/T7/BasicSettings/GetTeamInfo',{
      params:{
          TeamName:form.TeamName,
          TeamStatus:form.TeamStatus
      }
  }).then(res=>{
      tableData.value = res.data.data;
  })
}

//添加弹窗
const dialogFormVisible=ref(false)
//添加团队管理的参数
const teamform = reactive({
"teamName": "",
"teamPardName": "",
"teamTags": [],
"contactPhone": "",
"teamIntroduction": "",
"teamMembers": "",
"teamLeader": "",
"orgName": "",
"orgNamePard": null,
})


///// 新增成员选择相关变量
const memberDialogVisible = ref(false);
const showMemberDialog = () => {
memberDialogVisible.value = true;
};

//选择人员列表
const membersData = ref([])
const getUser=()=>{
axios.get(apiUrl+'/T7/Message/GetUserInfoList').then(res=>{
  membersData.value = res.data.data
})
}

const memberTableRef = ref(null); // 修改为正确的 ref 引用
const confirmMembers = () => {
const selectedRows = memberTableRef.value?.getSelectionRows() || [];
if (selectedRows.length === 0) {
  ElMessage.warning("请选择成员");
  return;
}
const names = selectedRows.map(row => row.nickName);
teamform.teamMembers = names.join(",");
memberDialogVisible.value = false;
};


//添加团队管理方法
const AddTeamInfo=()=>{
// 将数组类型的 teamTags 转换为字符串，假设用逗号分隔
const teamformWithConvertedTags:any = {...teamform };
  if (teamformWithConvertedTags.teamTags.length > 0) {
    teamformWithConvertedTags.teamTags = teamformWithConvertedTags.teamTags.join(',');
  } else {
    teamformWithConvertedTags.teamTags = '';
  }
  axios.post(apiUrl+'/T8/BasicSettings/TeamInfoAdd', teamformWithConvertedTags).then(res => {
        if (res.data.code == 212) {
          ElMessage.success(res.data.msg);
          dialogFormVisible.value = false;
          getTeamInfo();
           // 添加成功后刷新页面
          window.location.reload();
        }else if(res.data.code == 201)
        {
          ElMessage.error(res.data.msg);
          dialogFormVisible.value = false;
          getTeamInfo();
        }
         else {
          ElMessage.success("添加失败");
        }
      })
}



//删除
const DelTeamInfo=(id:number)=>{
  ElMessageBox.confirm(
    '确认删除这一条数据嘛?',
    '警告!警告!',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {

      axios.put(apiUrl+'/T8/BasicSettings/TeamInfoDel', { teamID: id }).then(res => {
      if (res.data.code === 204) {
        ElMessage({
        type: 'success',
        message: '恭喜你删除成功!',
      })
        getTeamInfo();
      } else {
        ElMessage({
        type: 'error',
        message: '很抱歉，删除失败!',
      })
      }
    })
    
    }).catch(() => {
      ElMessage({
        type: 'info',
        message: '取消成功！',
      })
    })

}

//启用禁用状态更改
const UdpTeamStatus=(id:number)=>{
  ElMessageBox.confirm(
    '确认要更改状态嘛?',
    '警告！警告！',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {

axios.put(apiUrl+'/T8/BasicSettings/UdpTeamStatus', { teamID: id }).then(res => {
      if (res.data.code === 206) {
        ElMessage({
        type: 'success',
        message: '恭喜你更改成功!',
      })
        getTeamInfo();
      } else {
        ElMessage({
        type: 'error',
        message: '很抱歉，更改失败!',
      })
      }
    })

    
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消成功',
      })
    })
}

//#region 修改操作
//修改的弹窗
const dialogFormUdp = ref(false)
//修改团队管理的参数
const teaminfo = reactive({
  "teamID": 0,
"teamName": "",
"teamPardName": "",
"teamTags": [],
"contactPhone": "",
"teamIntroduction": "",
"teamMembers": "",
"teamLeader": "李虎",
"orgName": "",
"orgNamePard": 0,
})
//反填团队管理数据
const fantian=(row:any)=>{
    console.log(row)
    dialogFormUdp.value = true
    teaminfo.teamID = row.teamID
    teaminfo.teamName = row.teamName
    teaminfo.teamPardName = row.teamPardName
    teaminfo.teamTags = row.teamTags ? row.teamTags.split(',') : []; 
    teaminfo.contactPhone = row.contactPhone
    teaminfo.teamIntroduction = row.teamIntroduction
    teaminfo.teamMembers = row.teamMembers
    teaminfo.teamLeader = row.teamLeader
    teaminfo.orgName = row.orgName
    teaminfo.orgNamePard = row.orgNamePard
}
//团队管理的修改
const UdpTeamInfo=()=>{
  // 将数组类型的 teamTags 转换为字符串，假设用逗号分隔
const teamformTags:any = {...teaminfo };
  if (teamformTags.teamTags.length > 0) {
    teamformTags.teamTags = teaminfo.teamTags.join(',');
  } else {
    teamformTags.teamTags = '';
  }
  axios.put(apiUrl+'/T8/BasicSettings/UdpTeamInfo', teamformTags).then(res => {
        if (res.data.code == 206) {
          ElMessage.success(res.data.msg);
          dialogFormUdp.value = false;
          getTeamInfo();
        } else {
          ElMessage.success("修改失败");
        }
      })
}
//#endregion



//#region 左侧树形显示
interface Tree {
  [key: string]: any
}

const filterText = ref('')
const treeRef = ref<TreeInstance>()
const data = ref<Tree[]>([]) // 改为响应式引用

const defaultProps = {
  children: 'children',
  label: 'orgName', // 根据接口字段修改为orgName
}

// 添加获取树形数据的方法
const fetchTreeData = async () => {
  try {
    const response = await axios.get(apiUrl+'/T7/BasicSettings/GetTeamTree')
    if (response.data.code === 210) {
      data.value = response.data.data.map(formatTreeData) // 转换数据结构
    }
  } catch (error) {
    ElMessage.error('获取组织树失败')
    console.error(error)
  }
}

// 转换数据结构，添加label字段
const formatTreeData = (node: any) => {
  return {
    ...node,
    label: node.orgName, // 将orgName映射为label
    children: node.children ? node.children.map(formatTreeData) : []
  }
}

watch(filterText, (val) => {
  treeRef.value!.filter(val)
})
//过滤查询
const filterNode = (value: string, data: Tree) => {
  if (!value) return true
  return data.orgName.includes(value) // 使用orgName进行过滤
}

//#endregion

//#region 左侧树形查询
// 调整后的点击事件处理
const handleNodeClick = async (nodeData: any) => {
  try {
    // 清空查询表单
    form.TeamName = "";
    form.TeamStatus = null;
    
    // 调用指定团队接口
    const response = await axios.get(apiUrl+'/T7/BasicSettings/GetTeamInfoById', {
      params: { 
        TeamID: nodeData.teamID // 确保树节点数据包含teamID
      }
    });
    
    // 处理响应数据
    if (response.data.code === 210) {
      tableData.value = response.data.data;
      //ElMessage.success(response.data.msg);
    } else {
      ElMessage.warning(`查询失败：${response.data.msg}`);
      tableData.value = []; // 清空表格
    }
  } catch (error) {
    console.error('节点点击查询异常:', error);
    ElMessage.error('团队信息查询失败，请检查网络连接');
    tableData.value = []; // 清空表格
  }
}


//#endregion



/////钩子函数
onMounted(()=>{
  getTeamInfo();//团队管理列表
  getUser();//用户列表选择
  fetchTreeData();//左侧树形
})


</script>

<style scoped>
.common-layout {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.side-panel {
  padding: 20px;
  background-color: #f5f7fa;
}

.main-container {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.search-header {
  padding: 20px;
  background-color: white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
}

.search-form {
  display: flex;
  align-items: center;
  gap: 20px;
}

.content-main {
  flex: 1;
  padding: 20px;
  background-color: #f9f9f9;
}

.tree-container {
  min-height: 400px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
}

.form-group {
  padding: 20px;
}

.form-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin: 20px 0 12px;
  border-bottom: 2px solid #f0f2f5;
  padding-bottom: 8px;
}

.tag-group {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.action-bar {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>    